package mi.payment.utils;

import com.sunmi.pay.hardware.aidl.bean.CardInfo;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import lainey.ui.utils.LogUtil;
import mi.payment.Constant;

public class Track2Util {

    /**
     * 解析二磁数据
     */
    public static CardInfo parseTrack2(String track2) {
        LogUtil.d(Constant.TAG, "track2:" + track2);
        if (track2 == null || track2.trim().length() < 13) {
            return new CardInfo();
        }
        track2 = stringFilter(track2);
        int index = track2.indexOf("=");
        if (index == -1) {
            index = track2.indexOf("D");
        }
        CardInfo cardInfo = new CardInfo();
        if (index == -1) {
            return cardInfo;
        }

        String cardNumber = "";
        if (track2.length() > index) {
            cardNumber = track2.substring(0, index);
        }
        String expiryDate = "";
        if (track2.length() > index + 5) {
            expiryDate = track2.substring(index + 1, index + 5);
        }
        String serviceCode = "";
        if (track2.length() > index + 8) {
            serviceCode = track2.substring(index + 5, index + 8);
        }
        LogUtil.d(Constant.TAG, "cardNumber:" + cardNumber + " expireDate:" + expiryDate + " serviceCode:" + serviceCode);
        cardInfo.cardNo = cardNumber;
        cardInfo.expireDate = expiryDate;
        cardInfo.serviceCode = serviceCode;
        return cardInfo;
    }

    /**
     * 只允许数字和=号,D
     */
    public static String stringFilter(String str) {
        String regEx = "[^0-9=D]";
        Pattern p = Pattern.compile(regEx);
        Matcher matcher = p.matcher(str);
        return matcher.replaceAll("").trim();
    }

    /**
     * 服务代码（SC） 第一位
     * 如果卡片仅含有磁条，不含有芯片，那么服务码仅可以是1或5开头。
     * 如果卡片含有芯片，那么服务码仅可以是2或6开头。
     *
     * @param track2 二磁
     */
    public static boolean isChipCard(String track2) {
        if (track2 == null || track2.length() == 0) {
            return false;
        }
        int index = track2.indexOf("=");
        if (index < 0) {
            return false;
        }
        String num = track2.substring(index + 5, index + 6);
        return "2".equals(num) || "6".equals(num);
    }

}
